// controllers/poiController.js
const db = require('../db');

async function getAllPOIs(req, res) {
  try {
    const [rows] = await db.query('SELECT id, shop_name, category, longitude, latitude FROM wuhan_food');
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error(error);
    res.status(500).json({ success: false, error: '数据库查询失败' });
  }
}

async function searchPOIs(req, res) {
  try {
    const {
      shop_name,
      category,
      region,
      business_hours,
      cuisine_type,
      min_people,
      max_people,
      min_price,
      max_price,
      recommend_level
    } = req.query;

    let sql = 'SELECT * FROM wuhan_food WHERE 1=1';
    const params = [];

    // 店铺名模糊查询
    if (shop_name) {
      sql += ' AND shop_name LIKE ?';
      params.push(`%${shop_name}%`);
    }

    if (category) {
      sql += ' AND category = ?';
      params.push(category);
    }

    if (region) {
      sql += ' AND region = ?';
      params.push(region);
    }

    // 营业时间模糊匹配关键字
    if (business_hours) {
      let keyword = '';
      if (business_hours === '早餐') keyword = '早';
      else if (business_hours === '午餐') keyword = '午';
      else if (business_hours === '晚餐') keyword = '晚';
      else if (business_hours === '夜宵') keyword = '夜';
      if (keyword) {
        sql += ' AND business_hours LIKE ?';
        params.push(`%${keyword}%`);
      }
    }

    if (cuisine_type) {
      sql += ' AND cuisine_type LIKE ?';
      params.push(`%${cuisine_type}%`);
    }

    // 人数范围 ±1 匹配
    if (min_people) {
      sql += ' AND (min_people <= ? + 1)';
      params.push(min_people);
    }
    if (max_people) {
      sql += ' AND (max_people >= ? - 1)';
      params.push(max_people);
    }

    // 价格范围 ±10 匹配（用户可以只填最低或最高）
    if (min_price) {
      sql += ' AND (min_price <= ? + 10)';
      params.push(min_price);
    }
    if (max_price) {
      sql += ' AND (max_price >= ? - 10)';
      params.push(max_price);
    }

    if (recommend_level) {
      sql += ' AND recommend_level LIKE ?';
      params.push(`%${recommend_level}%`);
    }

    const [rows] = await db.query(sql, params);
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error(err);
    res.status(500).json({ success: false, error: '数据库查询错误' });
  }
}


module.exports = { getAllPOIs ,searchPOIs};